<template>
  <div>
    <!-- 面包屑导航 -->
    <Breadcrumb />
    <!-- 卡片视图区域 -->
    <el-card shadow="always">
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索与添加区域 -->
          <el-input
            placeholder="请输入内容"
            @keyup.enter.native="getUserList"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              style="background: #66b1ff; color: #ffff"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table border :data="userList">
        <el-table-column
          align="center"
          type="index"
          label="序号"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="username"
          label="姓名"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="email"
          label="邮箱"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="mobile"
          label="电话"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="role_name"
          label="角色"
        ></el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.mg_state"
              active-color="#409eff"
              inactive-color="#ff4949"
              @change="userStatusChange(row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="修改"
              placement="top"
            >
              <el-button
                type="primary"
                @click="showEditDialog(row)"
                icon="el-icon-edit"
                circle
              ></el-button>
            </el-tooltip>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                title="删除"
                icon="el-icon-delete"
                @click="deleteUser(row.id)"
                circle
              ></el-button>
            </el-tooltip>

            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                @click="setRole(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5]"
        :page-size="queryInfo.pagesize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加或修改用户的对话框 -->
    <el-dialog
      :title="isEdit ? '编辑用户' : '添加用户'"
      :visible.sync="addOrUpdateDialogVisible"
      width="50%"
      @close="resetData"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addOrUpdateForm"
        :rules="rules"
        ref="addOrUpdateFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addOrUpdateForm.username"
            :disabled="isEdit"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="addOrUpdateForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addOrUpdateForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addOrUpdateForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addOrUpdateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="resetInfo"
    >
      <p class="pp">当前用户:{{ userInfo.username }}</p>
      <p class="pp">当前角色:{{ userInfo.role_name }}</p>
      <p class="pp">
        分配新角色：
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    let checkEmail = (rule, value, cb) => {
      const regEmail =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    let checkMobile = (rule, value, cb) => {
      const regMobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 3,
      },
      userList: [],
      total: 0,
      addOrUpdateDialogVisible: false, //控制显示添加或修改对话框
      addOrUpdateForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      isEdit: false, //是否是修改模式
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //控制分配角色对话框显示与隐藏
      setRoleDialogVisible: false,
      userInfo: {},
      rolesList: [],
      //选择角色的id
      value: "",
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //获取用户列表
    async getUserList() {
      try {
        const res = await this.$http.reqUserInfo(this.queryInfo);
        if (res.meta.status === 200) {
          this.userList = res.data.users;
          this.total = res.data.total;
        }
      } catch (error) {
        this.$message({
          message: "获取用户列表失败",
          type: "error",
        });
      }
    },
    //每页数据发生改变回调
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    //当前页改变回调
    handleCurrentChange(page) {
      this.queryInfo.pagenum = page;
      this.getUserList();
    },
    //修改用户状态
    async userStatusChange(row) {
      const res = await this.$http.updateUserStatus(row.id, row.mg_state);
      if (res.meta.status !== 200) {
        return this.$message({
          message: "修改失败",
          type: "error",
        });
      }
      this.$message({
        message: "更新用户状态成功",
        type: "success",
      });
      row.mg_state = !row.mg_state;
      this.getUserList();
    },
    //点击添加用户
    addUser() {
      this.addOrUpdateDialogVisible = true;
    },
    //重置添加对话框
    resetData() {
      this.$nextTick(() => {
        this.$refs.addOrUpdateFormRef.resetFields();
        this.isEdit = false;
        this.addOrUpdateForm = {
          username: "",
          password: "",
          email: "",
          mobile: "",
        };
      });
    },
    //添加或修改用户信息
    addOrUpdateUserInfo() {
      const { id } = this.addOrUpdateForm;
      const { isEdit } = this;
      this.$nextTick(() => {
        this.$refs.addOrUpdateFormRef.validate(async (valid) => {
          if (valid) {
            if (isEdit) {
              const res = await this.$http.updateUserInfo(
                id,
                this.addOrUpdateForm
              );
              if (res.meta.status !== 200) {
                return this.$message.error("修改失败");
              }
              this.$message.success("更改用户信息成功");
              this.addOrUpdateDialogVisible = false;
              this.getUserList();
            } else {
              const res = await this.$http.addUser(this.addOrUpdateForm);
              if (res.meta.status !== 201) {
                return this.$message.error("添加失败");
              }

              this.$message.success("添加用户信息成功");
              this.addOrUpdateDialogVisible = false;
              this.getUserList();
            }
          } else {
            this.$message.error(isEdit ? "修改失败" : "添加失败");
            return false;
          }
        });
      });
    },
    //打开修改用户信息对话框
    showEditDialog(row) {
      this.isEdit = true;
      this.addOrUpdateForm = { ...row };
      this.addOrUpdateDialogVisible = true;
    },
    //删除用户
    deleteUser(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.deleteUser(id);
          if (res.meta.status === !200) {
            this.$message.error("删除用户失败");
          }
          this.$message.success("删除用户成功");
          this.getUserList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //点击分配角色按钮
    async setRole(row) {
      this.userInfo = row;
      //获取所有角色列表
      const res = await this.$http.getAllRole();
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data;
      this.setRoleDialogVisible = true;
    },
    //点击分配角色对话框确定按钮
    async saveRoleInfo() {
      if (!this.value) {
        return this.$message.warning("请选择角色");
      }
      const res = await this.$http.setRole(this.userInfo.id, {
        rid: this.value,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("分配角色失败");
        this.setRoleDialogVisible = false;
      }
      this.$message.success("分配角色成功");
      this.setRoleDialogVisible = false;
      this.getUserList();
    },
    //关闭分配角色对话框
    resetInfo() {
      this.value = "";
      this.userInfo = {};
    },
  },
};
</script>

<style lang="less" scoped>
.el-pagination {
  margin-top: 30px;
  text-align: center;
}
.pp {
  font-size: 16px;
  margin-top: 10px;
}
</style>
